package org.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dao.StudentDao;
import org.example.entity.StudentEntity;
import org.example.config.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity> implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public boolean addStudent(StudentEntity studentEntity) {
        // 使用 MD5 加密密码
        studentEntity.setPassword(MD5Utils.encrypt(studentEntity.getPassword()));
        return studentDao.insert(studentEntity) > 0;
    }

    @Override
    public boolean updateStudent(StudentEntity studentEntity) {
        // 如果密码字段不为空，则加密后更新
        if (studentEntity.getPassword() != null) {
            studentEntity.setPassword(MD5Utils.encrypt(studentEntity.getPassword()));
        }
        return studentDao.updateById(studentEntity) > 0;
    }

    @Override
    public StudentEntity login(String username, String password) {
        QueryWrapper<StudentEntity> queryWrapper = Wrappers.query();
        queryWrapper.eq("stu_realname", username);
        StudentEntity student = studentDao.selectOne(queryWrapper);
        // 检查用户是否存在并验证密码
        if (student != null && MD5Utils.encrypt(password).equals(student.getPassword())) {
            return student;
        }
        return null;
    }

    @Override
    public boolean deleteStudent(Integer studentId) {
        return studentDao.deleteById(studentId) > 0;
    }

    @Override
    public StudentEntity getStudentById(Integer studentId) {
        return studentDao.selectById(studentId);
    }

    @Override
    public List<StudentEntity> getAllStudents() {
        return studentDao.selectList(null);
    }
}
